package com.example.orderproject;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.orderproject.Bean.Menu;
import com.example.orderproject.Bean.MenuForm;
import com.example.orderproject.Bean.User;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private RelativeLayout activityMain;
    private Button addmenu;
    private ImageView imageMenu;
    private Button sumbitButton;
    private EditText menunameEdittext;
    private EditText menupriceEdittext;
    private Button querybutton;




    //申请两个权限，录音和文件读写
    //1、首先声明一个数组permissions，将需要的权限都放在里面
    String[] permissions = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO};
    //2、创建一个mPermissionList，逐个判断哪些权限未授予，未授予的权限存储到mPerrrmissionList中
    List<String> mPermissionList = new ArrayList<>();

    private final int mRequestCode = 100;//权限请求码

    private List<String> paths;
    private String filePath_1;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= 23) {//6.0才用动态权限
            requestAllPower2();
            requestAllPower1();

        }
        Bmob.initialize(this,"dc2904f179b87449f83932778d2deb0d");
        addmenu = (Button) findViewById(R.id.addmenu);
        imageMenu = (ImageView) findViewById(R.id.image_menu);
        menupriceEdittext = (EditText) findViewById(R.id.menuprice_edittext);
        querybutton=(Button)findViewById(R.id.query_button);
        menunameEdittext = (EditText) findViewById(R.id.menuname_edittext);
        sumbitButton = (Button) findViewById(R.id.sumbit_button);
        querybutton.setOnClickListener(this);
//        User user=new User();
//        user.setName("01");
//        user.setPassword("111");
//         user.save(new SaveListener<String>() {
//           @Override
//           public void done(String s, BmobException e) {
//               if(e==null){
//                   Toast.makeText(MainActivity.this, "添加数据成功", Toast.LENGTH_SHORT).show();
//
//               }else{
//                   Toast.makeText(MainActivity.this, "创建数据失败", Toast.LENGTH_SHORT).show();
//
//               }
//           }
//       });
        addmenu.setOnClickListener(this);
        sumbitButton.setOnClickListener(this);
    }

    public void requestAllPower1() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }


    }
    public void requestAllPower2() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.CALL_PHONE,
                                Manifest.permission.CAMERA}, 1);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addmenu:
                Intent intent = new Intent(MainActivity.this, PhotoSelectorActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("limit", 2 );//number是选择图片的数量
                startActivityForResult(intent, 0);
            break;
            case R.id.sumbit_button:
                final BmobFile bmobFile = new BmobFile(new File(filePath_1));
                bmobFile.uploadblock(new UploadFileListener() {
                    @Override
                    public void done(BmobException e) {
                        if(e==null){
                            //bmobFile.getFileUrl();
                            Menu menu = new Menu();
                            //注意：不能调用gameScore.setObjectId("")方法
                            menu.setMenu_name(menunameEdittext.getText().toString());
                            menu.setMenu_image(bmobFile);
                            menu.setPrice(menupriceEdittext.getText().toString());
                            menu.save(new SaveListener<String>() {
                                @Override
                                public void done(String objectId, BmobException e) {
                                    if(e==null){
                                        Toast.makeText(MainActivity.this, "创建数据成功", Toast.LENGTH_SHORT).show();
                                    }else{
                                        Toast.makeText(MainActivity.this, "创建数据失败", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                        }else{

                        }
                    }
                    @Override
                    public void onProgress(Integer value) {
                        // 返回的上传进度（百分比）
                    }
                });
                break;
            case R.id.query_button:
                startActivity(new Intent(MainActivity.this,MenuInFoActivity.class));
                break;
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    paths = (List<String>) data.getExtras().getSerializable("photos");//path是选择拍照或者图片的地址数组
                    if (paths.size()==1){
                        filePath_1=paths.get(0);
                        Bitmap bitmap1= BitmapFactory.decodeFile(paths.get(0));
                        imageMenu.setImageBitmap(bitmap1);

                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
